import React, { useState, useEffect, forwardRef } from "react";
import { getWarehouseList } from "./service";
import { Select } from "@/views/components/PrefixPlaceholder";

const { Option } = Select;
const WarehouseSelect = forwardRef(
	({ value, onChange, defaultValue, defaultValued, isDefault, width, size, placeholder }, ref) => {
		const [warehouseList, setWarehouseList] = useState([]);
		const [defaultValues, setDefaultValues] = useState("");

		useEffect(() => {
			getWarehouseFunc();
		}, []);

		const getWarehouseFunc = async () => {
			const { data = [], success } = await getWarehouseList(); // 假设getWarehouseList是一个获取仓库列表的异步函数
			if (success) {
				if (data) {
					const list = data.map(x => {
						x.label = x.warehouseName;
						x.value = x.id;
						return x;
					});
					setWarehouseList(list);
				}

				if (data.length > 0 && isDefault) {
					const defaultList = data?.filter(x => x.kind == 1 && x.isDefault == 0);
					setDefaultValues(defaultList.length ? defaultList[0].id : data[0].id);
					defaultValued(defaultList.length ? defaultList[0].id : data[0].id);
				}
			}
		};
		useEffect(() => {}, [defaultValues]);
		return (
			<>
				{!defaultValues && (
					<Select
						style={{ width: width ? width : "100%" }}
						options={warehouseList}
						placeholder={placeholder}
						size={size}
						value={value}
						onChange={onChange}
					>
						{/* {warehouseList.map(function (item) {
						return (
							<Option value={item.id} key={item.id}>
								{item.warehouseName}
							</Option>
						);
					})} */}
					</Select>
				)}
				{defaultValues && (
					<Select
						style={{ width: width ? width : "100%" }}
						placeholder={placeholder}
						size={size}
						allowClear
						options={warehouseList}
						value={value ? value : defaultValues}
						onChange={onChange}
						defaultValue={defaultValue}
					>
						{/* {warehouseList.map(function (item) {
						return (
							<Option value={item.id} key={item.id}>
								{item.warehouseName}
							</Option>
						);
					})} */}
					</Select>
				)}
			</>
		);
	}
);

export default WarehouseSelect;
